<?php
namespace app\common\model;
use think\Cache;
use think\Image;

/**
 * 系统设置模型
 */
class Setting extends BaseModel
{
    protected $name = 'setting';
    protected $createTime = false;

    /**
     * 设置项描述
     */
    private $describe = [
        'mode' => '功能设置',
        'sms' => '短信通知',
        'wxapptpl' => '微信小程序订阅消息',
        'wechattpl' => '微信公众号模板消息',
        'storage' => '上传设置',
        'store' => '站点设置',
        'trade' => '交易设置',
        'recharge' => '充值设置',
        'delivery' => '配送设置',
        'dealer' => '分销设置',
        'poster' => '海报设置',
        'free' => '免费吃',
        'payment' => '支付设置',
        'subscribe' => '关注回复',//公众号
        'menus' => '公众号菜单',
    ];

    /**
     * 获取器: 转义数组格式
     */
    public function getValuesAttr($value)
    {
        return json_decode($value, true);
    }

    /**
     * 修改器: 转义成json格式
     */
    public function setValuesAttr($value)
    {
        return json_encode($value);
    }

    /**
     * 获取指定项设置
     */
    public static function getItem($key, $wxapp_id = null)
    {
        $data = self::getAll($wxapp_id);
        return isset($data[$key]) ? $data[$key]['values'] : [];
    }

    /**
     * 获取设置项信息
     */
    public static function detail($key)
    {
        // 筛选条件
        $filter = [];
        $filter['key'] = $key;
        return self::where($filter)->find();
    }

    /**
     * 全局缓存: 系统设置
     */
    public static function getAll($wxapp_id = null)
    {
        $self = new static;
        is_null($wxapp_id) && $wxapp_id = $self::$wxapp_id;
        // 筛选条件
        $filter = [];
        if($wxapp_id < 1){
            $filter['wxapp_id'] = 0;
            $wxapp_id = 0;
        }
        if (!$data = Cache::get('setting_' . $wxapp_id)) {
            $data = array_column(collection($self::where($filter)->select())->toArray(), null, 'key');
            Cache::set('setting_' . $wxapp_id, $data);
        }
        return array_merge_multiple($self->defaultData(), $data);
    }

    /**
     * 更新系统设置
     */
    public function edit($key, $values)
    {
        //公众号菜单
        if($key == 'menus'){
            $result = $this->creatmMenu($values);
            if($result['errcode']!=0){
                $this->error = wx_err_msg($result['errcode']);
                return false;
            }
        }
        //关注公众号回复
        if($key == 'subscribe'){
            $values = $this->subscribe($values);
        }
        //如果是设置微信小程序订阅消息
        if($key == 'wxapptpl'){
            //验证是否添加餐饮服务类目
            if($msg = is_food_category()){
                $this->error = $msg;
                return false;   
            }
            $values = $this->wxapptpl($values);
        }
        //如果是设置海报
        if($key == 'poster'){
            if(empty($values['shop']['logo'])){
                $this->error = '门店图标不存在，请补充门店信息';
                return false;
            }
            $this->poster($values);
        }
        $wxapp_id = self::$wxapp_id;
        $wxapp_id < 1 && $wxapp_id = 0;
        $model = self::detail($key) ?: $this;
        // 删除系统设置缓存
        Cache::rm('setting_' . $wxapp_id);
        return $model->save([
            'key' => $key,
            'describe' => $this->describe[$key],
            'values' => $values,
            'wxapp_id' => $wxapp_id,
        ]) !== false;
    }

    /**
    * 自定义菜单 - 同步到微信端
    */
    private function creatmMenu($menu)
    {
        $access_token = getAccessToken(self::$wxapp_id,0);
        $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$access_token;
        $data = [
           'button' => $menu
        ];
        return json_decode(http_post($url,$data),true);
    }

    /**
     * 关注回复内容
     */
    private function subscribe($data)
    {
        if($data['type'] == 'text'){
            $data['content']['media_id'] = ''; 
            $data['content']['title'] = '';
            $data['content']['url'] = '';
            $data['content']['hurl'] = '';
            $data['content']['picurl'] = '';
        }else{
            if(!$material = Material::mediaId($data['content']['media_id'])){
                $this->error = '素材不存在';
                return false; 
            }
            //图片消息
            if($data['type'] == 'image' OR $data['type'] == 'voice'){
                $data['content']['description'] = ''; 
                $data['content']['title'] = '';
                $data['content']['url'] = '';
                $data['content']['hurl'] = '';
                $data['content']['picurl'] = '';
            }
            //视频消息
            if($data['type'] == 'video'){
                //获取视频素材内容
                $data['content']['title'] = $material['name'];
                $data['content']['description'] = $material['introduction'];
                $data['content']['url'] = '';
                $data['content']['hurl'] = '';
                $data['content']['picurl'] = '';
            }
            //图文消息
            if($data['type'] == 'news'){
                //获取视频素材内容
                $data['content']['picurl'] = $material['url'];
                $data['content']['url'] = $data['content']['url'] ? $data['content']['url'] : web_url();
                $data['content']['hurl'] = '';
            }
        }
        return $data;
    }

    /**
     * 服务类目设置
     */
    private function wxapptpl($values)
    {
        $headers = array(
            'Content-Type: application/json',
        );
        $access_token = getAccessToken();
        //获取帐号下的模板列表
        $url = 'https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate?access_token='.$access_token;
        $res = json_decode(curl($url),true);
        if($res['errcode']==0){
            //循环删除订阅消息模板
            for($n=0;$n<sizeof($res['data']);$n++){
                $url = 'https://api.weixin.qq.com/wxaapi/newtmpl/deltemplate?access_token='.$access_token;
                $data = [
                    'priTmplId' => $res['data'][$n]['priTmplId']
                ];
                $result = json_decode(http_post($url,$data,$headers),true);
            }
        }
        //添加商家接单通知
        $url = 'https://api.weixin.qq.com/wxaapi/newtmpl/addtemplate?access_token='.$access_token;
        $data = [
            'tid' => '7942',
            'kidList' => [2,6,7,10,5],
            'sceneDesc' => '商家接单通知'
        ];
        $result = json_decode(http_post($url,$data,$headers),true);
        if($result['errcode']==0){
            $values['receive'] = $result['priTmplId'];
        }
        //添加骑手取货通知
        $url = 'https://api.weixin.qq.com/wxaapi/newtmpl/addtemplate?access_token='.$access_token;
        $data = [
            'tid' => '8927',
            'kidList' => [1,2,4],
            'sceneDesc' => '骑手取货通知'
        ];
        $result = json_decode(http_post($url,$data,$headers),true);
        if($result['errcode']==0){
            $values['horseman'] = $result['priTmplId'];
        }
        //添加订单完成通知
        $url = 'https://api.weixin.qq.com/wxaapi/newtmpl/addtemplate?access_token='.$access_token;
        $data = [
            'tid' => '677',
            'kidList' => [13,11,14,12,5],
            'sceneDesc' => '订单完成通知'
        ];
        $result = json_decode(http_post($url,$data,$headers),true);
        if($result['errcode']==0){
            $values['finish'] = $result['priTmplId'];
        }
        //添加取餐提醒
        $url = 'https://api.weixin.qq.com/wxaapi/newtmpl/addtemplate?access_token='.$access_token;
        $data = [
            'tid' => '250',
            'kidList' => [23,12,30,16,7],
            'sceneDesc' => '取餐提醒'
        ];
        $result = json_decode(http_post($url,$data,$headers),true);
        if($result['errcode']==0){
            $values['take'] = $result['priTmplId'];
        }
        //添加订单配送通知
        $url = 'https://api.weixin.qq.com/wxaapi/newtmpl/addtemplate?access_token='.$access_token;
        $data = [
            'tid' => '584',
            'kidList' => [1,2,15,4,5],
            'sceneDesc' => '订单配送通知'
        ];
        $result = json_decode(http_post($url,$data,$headers),true);
        if($result['errcode']==0){
            $values['delivery'] = $result['priTmplId'];
        }
        //退款状态通知
        $url = 'https://api.weixin.qq.com/wxaapi/newtmpl/addtemplate?access_token='.$access_token;
        $data = [
            'tid' => '8995',
            'kidList' => [1,2,4,5],
            'sceneDesc' => '退款状态通知'
        ];
        $result = json_decode(http_post($url,$data,$headers),true);
        if($result['errcode']==0){
            $values['refund'] = $result['priTmplId'];
        }
        return $values;
    }
    
    /**
     * 合成商家海报模板
     */
    private function poster($values)
    {
        header('Content-Type: image/png;charset=utf-8');//输出协议头
        $bg_path = './assets/store/img/dealer/poster.png';
        //生成临时缩略图
        if($values['shop']['file_name'] == 'no'){ 
            $file_url == './assets/images/shop_logo.png'; 
        }else if($values['shop']['file_name'] == 'wx'){
            $file_url == './assets/poster/temp/'.'wx'.$values['shop']['shop_id'].'.png';
            $content = file_get_contents($values['shop']['file_path']);
            file_put_contents($file_url, $content); 
        }else{
            $file_url = './uploads/'.$values['shop']['file_name'];
        }
        $image = Image::open($file_url);//读取原图
        $url = './assets/poster/temp/'.'shop_logo'.$values['shop']['shop_id'].'.png';
        $image->thumb(60,60)->save($url);
        yuan_img($url);
        //创建图片的实例
        $bg = imagecreatefromstring(file_get_contents($bg_path));//读取背景图片数据流
        $logo = imagecreatefromstring(file_get_contents($url));//读取二维码数据流
        //获取水印图片的宽高
        list($src_w, $src_h) = getimagesize($url);
        //将水印图片复制到目标图片上，最后个参数100是设置透明度，这里实现不透明效果
        //imagecopymerge($bg, $logo, 1360, 833, 0, 0, $src_w, $src_h, 100);
        //如果水印图片本身带透明色，则使用imagecopy方法
        imagecopy($bg, $logo, 40, 976, 0, 0, $src_w, $src_h);
        //设置水印文字颜色
        //SIMYOU.TTF 是幼圆字体
        $col = imagecolorallocatealpha($bg,255,255,255,0);
        //添加水印文字
        //30 是字体大小
        //215横坐标
        //875 980 是纵坐标
        $b = strlen($values['shop']['shop_name']);//计算有几个汉子
        $x = (750-$b/3*55)/2;
        $heiti = WEB_PATH . 'assets/plugins/fonts/heiti.ttf';
        //imagettftext(画布,字体大小单位磅,旋转角度,x坐标,y坐标,字体颜色,)
        imagettftext($bg,40,0,$x,325,$col,$heiti,$values['shop']['shop_name']);
        $col = imagecolorallocatealpha($bg,0,0,0,0);
        imagettftext($bg,15,0,110,1020,$col,$heiti,$values['shop']['shop_name']);
        $address = '地址：'.$values['shop']['address'];
        $x = 110+$b/3*23+20;
        imagettftext($bg,12,0,$x,1005,$col,$heiti,$address);
        $phone = '电话：'.$values['shop']['phone'];
        imagettftext($bg,12,0,$x,1035,$col,$heiti,$phone);
        //输出图片
        imagepng($bg,'assets/poster/'.self::$wxapp_id.'.png');
        //将数据进行销毁
        imagedestroy($bg);
        imagedestroy($logo);
    }

    /**
     * 默认配置
     */
    public function defaultData()
    {
		$values = WebSet::getItem('web');//获取站点配置
        return [
            'store' => [
                'key' => 'store',
                'describe' => '站点设置',
                'values' => ['name' => $values['name']],
            ],
            'payment' => [
                'key' => 'payment',
                'describe' => '支付设置',
                'values' => [
                    'wx' => [
                        'is_sub' => 0, //是否为特约商户
                        'mchid' => '',//商户号
                        'apikey' => '',//密钥
                        'cert_pem' => '', //apiclient_cert.pem 证书
                        'key_pem' => '' //apiclient_key.pem 密钥
                    ],
                    'postpaid' => [0,0,0]
                ]
            ],
            'trade' => [
                'key' => 'trade',
                'describe' => '交易设置',
                'values' => [
                    'order' => [
                        'time' => '10',//任务执行间隔
                        'close_time' => '60',//未支付订单关闭时间
                        'delivery_time' => '60',//已配送订单自动配送完成时间
                        'receive_time' => '60', //配送完毕订单用户自动确认收货时间 
                        'cmt_time' => '1440', //收货订单用户自动评价时间
                        'refund_time' => '0' //退款订单自动退款时间
                    ],
                    'freight_rule' => '10',
                ]
            ],
			'delivery' => [
                'key' => 'delivery',
                'describe' => '配送设置',
                'values' => [
					'delivery_range' => '3000',	//配送范围
					'free_range' => '0',		//免费配送范围
                    'delivery_price' => '5',	//配送费用
					'min_price' => '15',		//起送价格
                ]
            ],
            'storage' => [
                'key' => 'storage',
                'describe' => '上传设置',
                'values' => [
                    'default' => 'local',
                    'engine' => [
                        'qiniu' => [
                            'bucket' => '',
                            'access_key' => '',
                            'secret_key' => '',
                            'domain' => 'http://'
                        ],
                    ]
                ],
            ],
            'menus' => [
                'key' => 'menus',
                'describe' => '公众号菜单',
                'values' => [
                /*  0 => [
                        "type" => "view",
                        "name" => "一级菜单",
                        "sub_button" => [
                            0 => [
                                "type" => "click",
                                "name" => "二级菜单",
                                "key" => "关键字"
                            ],
                        ],
                        "url" => web_url()
                    ]*/
                ],
            ],
            'subscribe' => [
                'key' => 'subscribe',
                'describe' => '关注回复',
                'values' => [
                    'is_open' => 1,     //是否开启 0=关闭，1=开启
                    'type' => 'text',   //消息类型 text=文字消息,image=图片消息,news=图文消息,voice=声音消息
                    'content' => [
                        'media_id' => '',//素材
                        'title' => '',//标题
                        'description' => '谢谢关注',//描述或回复内容
                        'url' => '',//链接网址
                        'hurl' => '',//音乐缩略图
                        'picurl' => ''//图片网络地址
                    ]
                ]
            ],
            'sms' => [
                'key' => 'sms',
                'describe' => '短信通知',
                'values' => [
                    'default' => 'aliyun',
                    'engine' => [
                        'aliyun' => [
                            'AccessKeyId' => '',
                            'AccessKeySecret' => '',
                            'sign' => $values['name'],
                            'order_pay' => [
                                'is_enable' => '0',
                                'template_code' => '',
                                'accept_phone' => '',
                            ],
                        ],
                    ],
                ],
            ],
			'wxapptpl' => [
                'key' => 'wxapptpl',
                'describe' => '微信小程序订阅消息',
                'values' => [
                    'receive' => '',//商家接单通知
                    'horseman' => '',//骑手取货通知
                    'delivery' => '',  //订单配送通知
                    'take' => '',  //取餐提醒
                    'finish' => '',  //订单完成通知
					'refund' => '',  //退款状态通知
                ],
            ],
            'wechattpl' => [
                'key' => 'wechattpl',
                'describe' => '微信公众号模板消息',
                'values' => [
                    'receive' => '',//商家接单通知
                    'horseman' => '',//骑手取货通知
                    'delivery' => '',  //订单配送通知
                    'take' => '',  //取餐提醒
                    'finish' => '',  //订单完成通知
                    'refund' => '',  //退款状态通知
                ],
            ],
			'free' => [
                'key' => 'free',
                'describe' => '免费吃',
                'values' => [
                    'is_open' => 0,	//是否开启
					'title' => '免费吃',//标题
					'detail' => '指定商品在活动期内，如您订购该商品，后续又有他人下单此商品，达到指定数量后您的该商品免费，依此循环。购买该商品的费用会返还至您的账户余额内。',//规则说明
					'start_time' => '',	//开始时间
					'end_time' => '',	//结束
                ],
            ],
			'recharge' => [
                'key' => 'recharge',
                'describe' => '充值设置',
                'values' => [
                    'is_open' => 1,		//是否开启
					'is_custom' => 1,	//是否允许用户自定义金额
					'is_match_plan' => 1,	//是否自动匹配套餐
					'describe' => '1. 账户充值仅限微信在线方式支付，充值金额实时到账；
2. 账户充值套餐赠送的金额即时到账；
3. 账户余额有效期：自充值日起至用完即止；
4. 若有其它疑问，可拨打客服电话400-000-1234',	//充值说明
                ],
            ],
			'dealer' => [
                'key' => 'dealer',
                'describe' => '分销设置',
                'values' => [
                    'is_open' => 0,  //是否开启分销功能
                    'first_money' => 5,  //一级佣金比例
                    'second_money' => 5,  //二级佣金比例
                    'min_money' => 100,  //最低提现额度
                ],
            ],
            'poster' => [
                'key' => 'poster',
                'describe' => '海报设置',
                'values' => [
                    'backdrop' => [
                        'src' => web_url().'assets/store/img/dealer/poster.png',
                    ],
                    'nickName' => [
                        'fontSize' => 14,
                        'color' => '#FFFFFF',
                        'left' => 150,
                        'top' => 99,
                    ],
                    'avatar' => [
                        'width' => 70,
                        'style' => 'circle',
                        'left' => 150,
                        'top' => 18,
                    ],
                    'qrcode' => [
                        'width' => 160,
                        'style' => 'circle',
                        'left' => 108,
                        'top' => 190,
                    ],
					'shop' => [
						'shop_id' => '',
                        'shop_name' => '',
                        'address' => '',
                        'phone' => '',
                        'file_name' => '',
						'logo' => '',
                    ],
                ],
            ],
        ];
    }

}
